package com.liao.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liao.dao.ProvinceDao;
import com.liao.dao.impl.ProvinceDaoImpl;
import com.liao.domain.Province;
import com.liao.service.ProvinceService;
import com.liao.utils.JedisPoolUtils;
import redis.clients.jedis.Jedis;

import java.util.List;

public class ProvinceServiceImpl implements ProvinceService {
    //声明dao
    private ProvinceDao dao = new ProvinceDaoImpl();

//    @Override
//    public List<Province> findAllCity() {//调用dao的findAllCity方法查询数据库
//        return dao.findAllCity();
//    }

    @Override
    public String findAllJson() {//使用redis缓存返回数据
        //1. 先从redis中查询数据
        //1.1 获取redis客户端连接
        Jedis jedis = JedisPoolUtils.getJedis();
        String province_json = jedis.get("province");
        //2 判断province_json数据是否为null
        if(province_json==null || province_json.length()==0){
            //redis中没有数据
            System.out.println("redis中没有，查询DB");
            //2.1从数据库中查询
            List<Province> ps = dao.findAllCity();
            //2.2将list序列化为json
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                province_json = objectMapper.writeValueAsString(ps);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            //2.3将json数据存入redis中
            jedis.set("province",province_json);
        }else{
            System.out.println("redis中有数据");
        }
        jedis.close();
        return province_json;
    }
}
